package tech.cutu.lessons.thinking.in.spring.ioc.overview.dependency.lookup;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import tech.cutu.lessons.thinking.in.spring.ioc.overview.domain.User;

import java.util.Map;

/**
 * 通过名称
 * 依赖查找实例
 *
 *
 */
public class DependencyLookupDemo {

    public static void main(String[] args) {
        // 配置xml配置文件,启动Spring应用上下文
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/dependency-lookup-context.xml");

        // 实时查找
        lookupInRealTime(beanFactory);

        lookupInLazy(beanFactory);


        // 通过类型
        lookupByType(beanFactory);
        
        lookupCollectionByType(beanFactory);

    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
            System.out.println(users);
        }

    }

    private static void lookupByType(BeanFactory beanFactory) {
        User u = (User) beanFactory.getBean("user");

        System.out.println("实时查找：" + u);

    }


    public static void lookupInRealTime(BeanFactory beanFactory){
        User u = beanFactory.getBean(User.class);

        System.out.println("通过Bean类型实时查找：" + u);
    }

    public static void lookupInLazy(BeanFactory beanFactory){
        ObjectFactory<User> objectFactory = (ObjectFactory<User>) beanFactory.getBean("objectFactory");
        User u = objectFactory.getObject();

        System.out.println("延迟查找：" + u);
    }

}
